package com.mall.order.biz.handler;

import com.mall.commons.result.ResponseUtil;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.ClearCartItemRequest;
import com.mall.shopping.dto.ClearCartItemResponse;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *  ciggar
 * create-date: 2019/8/1-下午5:05
 * 将购物车中的缓存失效
 */
@Slf4j
@Component
public class ClearCartItemHandler extends AbstractTransHandler {

    @Autowired  //用于操作redis数据库
    private RedissonClient redissonClient;

    //是否采用异步方式执行
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext orderContext = (CreateOrderContext) context;

        //获得当前用户所有订单
        RMap<Object, Object> map = redissonClient.getMap(String.valueOf(orderContext.getUserId()));

        //获得要清楚购物车中的商品的商品id,并删除
        List<Long> productIds = orderContext.getBuyProductIds();

        if(productIds.size() == 0){
            return false;
        }

        for (Long productId : productIds) {
            map.remove(productId);
        }

        return true;

    }
}

